package yzx.firstletter.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.graphics.BitmapCompat;
import android.support.v4.util.LruCache;

import java.util.ArrayList;
import java.util.List;

public class AppInstallUtil {

    public static class AppInfo{
        public String packageName;
        public String name;
    }


    public static List<AppInfo> getAllInstalledAppInfo(Context context, boolean containSelf){
        List<PackageInfo> infos = context.getPackageManager().getInstalledPackages(PackageManager.GET_GIDS);
        if(infos==null || infos.isEmpty())
            return null;
        String mPackageName = context.getPackageName();
        ArrayList<AppInfo> result = new ArrayList<>();
        boolean hasPassSelf = false;
        for (PackageInfo item : infos) {
            if(!hasPassSelf && !containSelf && item.packageName.equals(mPackageName)){
                hasPassSelf=true;
                continue;
            }
            AppInfo ai = new AppInfo();
            ai.packageName = item.packageName;
            ai.name = item.applicationInfo.loadLabel(context.getPackageManager()).toString();
            result.add(ai);
        }
        return result;
    }



    private static final LruCache<String, Drawable> appIconCache = new LruCache<String, Drawable>(1024*1024*5){
        @Override
        protected int sizeOf(String key, Drawable value) {
            return BitmapCompat.getAllocationByteCount(((BitmapDrawable)value).getBitmap());
        }
    };
    /**
     * 根据包名 获取 icon
     * @return 如果获取失败, 返回null
     */
    public static Drawable getIconByPackage(Context context, String pckName) {
        Drawable d = appIconCache.get(pckName);
        if (d != null) return d;
        PackageManager manager = context.getPackageManager();
        try {
            Drawable icon = manager.getApplicationIcon(pckName);
            if (icon != null) appIconCache.put(pckName, icon);
            return icon;
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }

}
